<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" title="编辑配置" width="700px" @ok="handleSubmit" destroyOnClose>
    <MyAlert 
      type="warning" 
      style="margin-bottom: -5px"
      message="对于敏感信息，将不会在页面上展示，但你可以直接输入新值进行更新配置，比如：微信公众号的AppSecret" 
    />
    <DiyFormRender
      v-if="record"
      :form-id="record?.diyFormId"
      :fixedInFront="true"
      diy-field-name="fields"
      :beforeFormSchema="beforeFormSchema"
      :afterFormSchema="afterFormSchema"
      ref="diyFormRenderRef"
    >
    </DiyFormRender>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, onUnmounted, useAttrs, nextTick } from "vue"
  import MyAlert from "/@/components/My/MyAlert.vue"
  import { beforeFormSchema, afterFormSchema } from "./data"
  import { BasicDrawer, useDrawerInner } from "/@/components/Drawer"
  import * as configApi from "/@/api/infra/config"
  import { useMessage } from "/@/hooks/web/useMessage"
  import DiyFormRender from "/@/views/diyDesigner/render-page/DiyFormRender.vue"

  const { createMessage } = useMessage()

  const emit = defineEmits(["success", "register"])
  const attrs = useAttrs()
  const rowId = ref("")
  const record = ref<any>({})
  const diyFormRenderRef = ref<InstanceType<typeof DiyFormRender>>()

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    record.value = null
    console.log("record", data.record)
    let showFooter = data?.showFooter ?? true
    setDrawerProps({ confirmLoading: false, showFooter, loading: true })
    try {
      record.value = await configApi.getConfigByKey(data.record.configKey)
      rowId.value = data.record.id

      nextTick(() => {
        diyFormRenderRef.value?.setValues({ ...record.value })
      })
    } finally {
      setDrawerProps({ loading: false })
    }
  })

  onUnmounted(() => {
    console.log('销毁抽屉')
  })

  async function handleSubmit() {
    setDrawerProps({ loading: true })
    try {
      let values = await diyFormRenderRef.value?.getValues()

      console.log("submit: ", values)
      await configApi.saveOrUpdate({ ...values }, true)

      closeDrawer()
      createMessage.success(`编辑成功`)
      emit("success", { ...values, id: rowId.value })
    } finally {
      setDrawerProps({ loading: false })
    }
  }
</script>
